package wpwork.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import wpwork.entity.AppVersionEntity;
import wpwork.entity.KshMessageEntity;
import wpwork.mapper.AppVersionMapper;
import wpwork.mapper.KshMessageMapper;
import wpwork.service.AppVersionService;
import wpwork.service.IKshMessageService;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

@Service
public class AppVersionServiceImpl extends ServiceImpl<AppVersionMapper, AppVersionEntity> implements AppVersionService {
    @Override
    public AppVersionEntity getInfo() {
        return this.getOne(new QueryWrapper<AppVersionEntity>()
                .orderByDesc("upload_time")
                .last("LIMIT 1"));
    }

    @Autowired
    private Environment environment;

    @Override
    public AppVersionEntity uploadFile(MultipartFile file, String version, String description, String downloadUrl) {
        if (file.isEmpty()) {
            throw new RuntimeException("上传文件不能为空");
        }

        try {
            // 获取配置的base-path
            String basePath = environment.getProperty("config.file-storage.local-plus[0].base-path");
            if (basePath == null) {
                throw new RuntimeException("未找到文件存储基础路径配置");
            }

            // 根据需求直接拼接路径，不添加分隔符
            Path targetDir = Paths.get(basePath + "WebAnnexFile");
            Files.createDirectories(targetDir);

            // 构建文件保存路径
            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String newFileName = System.currentTimeMillis() + fileExtension;
            Path targetPath = targetDir.resolve(newFileName);

            // 保存文件
            file.transferTo(targetPath);

            // 获取本机IP
            InetAddress localHost = InetAddress.getLocalHost();
            String ipAddress = localHost.getHostAddress();
            System.out.println("本机IP地址: " + ipAddress);


            // 创建或更新AppVersionEntity实体
            AppVersionEntity entity = new AppVersionEntity();
            entity.setSysVersion(version);
            String downUrl = "http://"+ipAddress+":"+environment.getProperty("server.port")+"/api/file/Image/annexpic/" + newFileName;
            entity.setUrl(downUrl);
            entity.setDescription(description);
            entity.setUploadTime(new Date());
            // 保存到数据库
            this.save(entity);

            return entity;
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败: " + e.getMessage(), e);
        }
    }

}
